package com.bw.module_cinema.model.adapter

import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bw.module_cinema.R
import com.bw.module_cinema.databinding.ItemVideoBinding
import com.bw.module_cinema.model.entity.VideoByTypeIdEntity

class VideoByTypeIdAdapter:RecyclerView.Adapter<VideoByTypeIdAdapter.VideoViewHolder>() {

    private val list = ArrayList<VideoByTypeIdEntity>()

    private var onStarClickListener: ((VideoByTypeIdEntity, Boolean) -> Unit)? = null

    // 暴露给外部设置回调
    fun setOnStarClickListener(listener: (VideoByTypeIdEntity, Boolean) -> Unit) {
        onStarClickListener = listener
    }

    interface OnVideoItemClickListener{
        fun onItemClick(entity: VideoByTypeIdEntity)
    }

    private var listener : OnVideoItemClickListener? = null

    fun setOnItemClickListener(listener: OnVideoItemClickListener) {
        this.listener = listener
    }

    fun setData(mList: List<VideoByTypeIdEntity>){
        list.clear()
        list.addAll(mList)
        notifyDataSetChanged()
    }
    
    fun updateItem(position: Int, isStar: Boolean) {
        if (position >= 0 && position < list.size) {
            list[position].isStar = isStar
            notifyItemChanged(position)
        }
    }

    class VideoViewHolder(
        val binding: ItemVideoBinding
    ) : RecyclerView.ViewHolder(binding.root)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VideoViewHolder {
        // 加载列表项布局
        val binding = ItemVideoBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return VideoViewHolder(binding)
    }

    override fun onBindViewHolder(holder: VideoViewHolder, position: Int) {

        val item = list[position]
        holder.binding.video = item
        holder.binding.executePendingBindings()

        // 使用实体类的收藏状态（从数据库加载）
        val isStar = item.isStar

        // 更新按钮图标（已收藏/未收藏）
        holder.binding.star.setImageResource(
            if (isStar) R.drawable.ic_star_red else R.drawable.star
        )

        // 点击star按钮切换收藏状态
        holder.binding.star.setOnClickListener {
            val newStarState = !item.isStar
            item.isStar = newStarState // 更新实体类的状态
            // 更新按钮图标
            holder.binding.star.setImageResource(
                if (newStarState) R.drawable.ic_star_red else R.drawable.star
            )
            // 回调给外部（Fragment）处理实际收藏逻辑
            onStarClickListener?.invoke(item, newStarState)
        }
        holder.itemView.setOnClickListener {
            listener?.onItemClick(item)
        }
    }

    override fun getItemCount(): Int {
        return list.size
    }

}